﻿using Furion.DataEncryption;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HongHui_WX.Web.Core.Middleware
{
    /// <summary>
    /// 用于过滤第三方请求,生成系统能够识别的Token
    /// </summary>
    public class TrustRequestMiddleware
    {
        private readonly RequestDelegate _next;

        public TrustRequestMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        /// <summary>
        /// 从context中解析用户信息后生成 JWT
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            var uid = context.Request.Headers["UID"];
            if (uid.Count > 0)
            {

                var accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>(){
                    { "userid",uid}
                });
                context.Request.Headers.Append("Authorization", $"Bearer {accessToken}");
            }
            await _next.Invoke(context);
        }
    }
}
